package com.itheima.controller;

import com.itheima.entity.Result;
import com.itheima.pojo.LoginDto;
import com.itheima.pojo.Member;
import com.itheima.pojo.User;
import com.itheima.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/member")
public class MemberLoginController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private MemberService memberService;

    @PostMapping("/login.do")
    public Result login(@RequestBody LoginDto loginDto) {
        //校验参数
        if (loginDto == null) {
            return new Result(false, "参数异常");
        }
        //判断验证码是否输入
        if (loginDto.getValidateCode() == null) {
            return new Result(false, "请输入验证码");
        }
        //获取session的验证码
        HttpSession session = request.getSession();
        String code = (String) session.getAttribute(loginDto.getTelephone());
        //判断验证码是否正确
        if (!code.equals(loginDto.getValidateCode())) {
            return new Result(false, "验证码错误");
        }
        //判断用户是否第一次登录 如果是则添加用户到数据库
        Member member = memberService.findByTelephone(loginDto.getTelephone());
        if (member == null) {
            Member newMember = memberService.register(loginDto.getTelephone());
            session.setAttribute("memberId", newMember.getId());
            return new Result(true, "登陆成功");
        }
        session.setAttribute("memberId", member.getId());
        return new Result(true, "登陆成功");
    }
}
